<template>
  <BasicDrawer
    :title="title"
    :width="adaptiveWidth"
    v-bind="attrs"
    @ok="methods.handleSubmit"
    @register="registerModel"
    :useWrapper="true"
    :show-footer="true"
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script setup lang="ts">
  import ApiV1 from '@/views/common/operate/ApiV1';
  import BasicForm from '@/components/Form/src/BasicForm.vue';
  import BasicDrawer from '@/components/Drawer/src/BasicDrawer.vue';
  import { useAttrs } from 'vue';
  import gloabComponentConfig from '@/settings/gloabComponentConfig';
  import { forEach, forIn, includes, isNil } from 'lodash-es';
  import { handleUpdateSchema } from '@/views/system/senior/menu/page.data';
  import { useMenusAddSchemaForm } from '@/api/http/system/senior/menus/menus.data';
  import {
    apiGetMenusDetailsPath,
    apiPostMenusAdd,
    apiPostMenusUpdatePath,
  } from '@/api/http/system/senior/menus/menus.api';
  import { useAutoAdaptWidth } from '@/hooks/system/useAutoAdapt';

  const { width: adaptiveWidth } = useAutoAdaptWidth(gloabComponentConfig.adaptiveWidth);
  const attrs = useAttrs();
  const emit = defineEmits(['success', 'register']);
  const { registerForm, registerModel, methods, formMethods, title } = ApiV1.useHandle(emit, {
    formProps: { schemas: useMenusAddSchemaForm(), baseColProps: { span: 8 } },
    title: '菜单',
    details: apiGetMenusDetailsPath,
    saveFn: apiPostMenusAdd,
    updateFn: apiPostMenusUpdatePath,
    mode: 'drawer',
    queryResult: async (res) => {
      forEach(res, (item, key) => {
        if (key != 'status') {
          if (typeof item == 'number') {
            res[key] = String(item);
          }
        }
      });
      return res;
    },
    afterQuery: async (res) => {
      if (res['isButton'] == '0') {
        handleUpdateSchema(formMethods, res['menuType']);
      }
      const meta = {};
      forIn(res.meta, (item, key) => {
        if (typeof item == 'boolean') {
          meta[key] = item == true ? 1 : 0;
        } else {
          meta[key] = item;
        }
      });

      await formMethods.setFieldsValue(meta);
    },
    beforeSubmit: async (values) => {
      const field = ['icon', 'frameSrc', 'hideTab', 'hideMenu', 'ignoreKeepAlive', 'orderNo'];
      forEach(field, (item) => {
        if (isNil(values['meta'])) {
          values['meta'] = {};
        }
        if (isNil(values['meta'][item])) {
          if (includes(['hideTab', 'hideMenu', 'ignoreKeepAlive'], item)) {
            values['meta'][item] = values[item] == '1';
          } else {
            values['meta'][item] = values[item];
          }
          delete values[item];
        }
      });
      if (isNil(values['meta']['title'])) {
        values['meta']['title'] = values['menuName'];
      }
      return values;
    },
  });
</script>
